//
//  Start.m
//  Speedater
//
//  Created by NgoThang on 12/28/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Start.h"
#import "asyncimageview.h"
#import "Imprint.h"
#import "AGB.h"
#import "PrivacyPolicy.h"
#import "UserProfile.h"
#import "Radar.h"
#import "Contact.h"
#import "AppDelegate.h"
#import "JSON.h"

@interface Start (Private)

- (void)cleanup;

@end

@implementation Start (Private)

- (void)cleanup
{
    self.myTabBar = nil;
    self.avatarImageView = nil;
    self.start1Label = nil;
    self.start2Label = nil;
    self.radarViewButton = nil;
    self.editProfileButton = nil;
    self.contactButton = nil;
    self.imprintButton = nil;
    self.agbButton = nil;
    self.privacyPolicyButton = nil;
}

@end


@implementation Start

@synthesize myTabBar;
@synthesize avatarImageView;
@synthesize start1Label, start2Label;
@synthesize radarViewButton, editProfileButton, contactButton, imprintButton, agbButton, privacyPolicyButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[UIApplication sharedApplication] setStatusBarHidden:YES];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc
{
    //NSLog(@"START -> dealloc");
    [self cleanup];
    [super dealloc];
}

#pragma mark - Custom functions

- (IBAction)radarViewButtonClick:(id)sender
{
    [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:NO];
    self.tabBarController.selectedIndex = 1;
}

- (IBAction)editProfileButtonClick:(id)sender
{
    UserProfile *userProfile = [[UserProfile alloc] init];
    [self.navigationController pushViewController:userProfile animated:YES];
    [userProfile release];
}

- (IBAction)contactButtonClick:(id)sender
{
    [[[[self.tabBarController.viewControllers objectAtIndex:2] topViewController] navigationController] popToRootViewControllerAnimated:NO];
    self.tabBarController.selectedIndex = 2;
}

- (IBAction)imprintButtonClick:(id)sender
{
    Imprint *imprint = [[Imprint alloc] init];
    [self.navigationController pushViewController:imprint animated:YES];
    [imprint release];
}

- (IBAction)agbButtonClick:(id)sender
{
    AGB *agb = [[AGB alloc] init];
    [self.navigationController pushViewController:agb animated:YES];
    [agb release];
}

- (IBAction)privacyPolicyButtonClick:(id)sender
{
    PrivacyPolicy *privacyPolicy = [[PrivacyPolicy alloc] init];
    [self.navigationController pushViewController:privacyPolicy animated:YES];
    [privacyPolicy release];
}

- (void)updateNewMails
{
    NSString *postString = [NSString stringWithFormat:@"op=loadNewMail&username=%@",[[NSUserDefaults standardUserDefaults] stringForKey:@"username"]];
    NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postString length]];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData]; 
    [request setTimeoutInterval:60.0];
    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    if (conn) {
        // init data    
        responseData = [[NSMutableData data ] retain];
        
        // loading
        UIWindow *theWindow = [UIApplication sharedApplication].keyWindow;
        HUD = [[MBProgressHUD alloc] initWithWindow:theWindow];
        [theWindow addSubview:HUD];
        HUD.delegate = self;
        [HUD show:YES];
    }
    [conn release];
}

- (void)goStart
{
    // update new mails
    [self updateNewMails];
    
    // get avatar image
    AsyncImageView *asyncImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(16, 10, 47, 43)];
    asyncImage.tag = 999;
	NSURL *avatarURL = [NSURL URLWithString: [NSString stringWithFormat:@"%@avatar/%@", 
                                              [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"], 
                                              [[NSUserDefaults standardUserDefaults] stringForKey:@"username"]]];
	[asyncImage loadImageFromURL:avatarURL];
    [asyncImage setForImage:avatarImageView];
    avatarImageView.contentMode = UIViewContentModeScaleAspectFit;
    [asyncImage release];
}

- (void)goBack
{
    // remove username and password
    [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@"username"];
    [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@"password"];
    
    // goto login form
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)dismissActionSheet:(id)sender
{
    [myActionSheet dismissWithClickedButtonIndex:1 animated:YES];
}

- (void)avatarClick
{
    myActionSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                delegate:nil
                                       cancelButtonTitle:nil
                                  destructiveButtonTitle:nil
                                       otherButtonTitles:nil];
    
    [myActionSheet setActionSheetStyle:UIActionSheetStyleBlackTranslucent];
    
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:avatarImageView.image] autorelease];
    imageView.frame = CGRectMake(10, 50, 300, 300);
    imageView.contentMode = UIViewContentModeScaleAspectFit;
    [myActionSheet addSubview:imageView];
    
    UISegmentedControl *closeButton = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObject:@"zurück"]];
    closeButton.momentary = YES; 
    closeButton.frame = CGRectMake(240, 7.0f, 70.0f, 30.0f);
    closeButton.segmentedControlStyle = UISegmentedControlStyleBar;
    closeButton.tintColor = [UIColor blackColor];
    [closeButton addTarget:self action:@selector(dismissActionSheet:) forControlEvents:UIControlEventValueChanged];
    [myActionSheet addSubview:closeButton];
    [closeButton release];
    
    [myActionSheet showInView:[[UIApplication sharedApplication] keyWindow]];
    
    [myActionSheet setBounds:CGRectMake(0, 0, 320, 685)];
}

- (void)start2LabelClick
{
    [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] popToRootViewControllerAnimated:NO];
    self.tabBarController.selectedIndex = 3;
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    //NSLog(@"START -> viewDidLoad");
    [super viewDidLoad];
    
    // navigation bar
    self.navigationController.navigationBar.hidden = NO;
    
    // background
    [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"background.png"]]];
    
    // navigation title
    self.title = @"Startseite";
    
    // navigation buttons
    UIButton *logoButton = [[UIButton alloc] initWithFrame:CGRectMake(0,2,35,35)];
    [logoButton setBackgroundImage:[UIImage imageNamed:@"logo.png"] forState:UIControlStateNormal];
    UIBarButtonItem *iLButton = [[UIBarButtonItem alloc] initWithCustomView:logoButton];
    [logoButton addTarget:self action:@selector(goStart) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = iLButton;
    [logoButton release];
    [iLButton release];
    
    UIButton *backButton = [UIButton buttonWithType:100];
    [backButton setTitle:@"Ausloggen" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *iRButton = [[UIBarButtonItem alloc] initWithCustomView: backButton];
    self.navigationItem.rightBarButtonItem = iRButton;
    [iRButton release];
    
    // avatar image click
    UITapGestureRecognizer *tgr = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(avatarClick)] autorelease];
    [self.avatarImageView addGestureRecognizer:tgr];
    [avatarImageView setUserInteractionEnabled:YES];
    
    // update username
    NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
    NSString *str1 = [[NSString alloc] initWithFormat:@"Willkommen, %@", [def stringForKey:@"username"]];
    [self.start1Label setText:str1];
    [str1 release];
    
    // start2Label click
    UITapGestureRecognizer *tgr1 = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(start2LabelClick)] autorelease];
    [self.start2Label addGestureRecognizer:tgr1];
    [self.start2Label setUserInteractionEnabled:YES];
}

- (void)viewDidUnload
{
    //NSLog(@"START -> viewDidUnload");
    [self cleanup];
    [super viewDidUnload];
}

- (void)viewWillAppear:(BOOL)animated
{
    //NSLog(@"START -> viewWillAppear");
    //NSLog(@"START -> viewControllers: %@", self.navigationController.viewControllers);
    
    [AppDelegate saveState:0 withViewController:self];
    
    // update new mails
    [self updateNewMails];
    
    // get avatar image
    AsyncImageView *asyncImage = [[AsyncImageView alloc] initWithFrame:CGRectMake(16, 10, 47, 43)];
    asyncImage.tag = 999;
	NSURL *avatarURL = [NSURL URLWithString: [NSString stringWithFormat:@"%@avatar/%@", 
                                              [[NSUserDefaults standardUserDefaults] stringForKey:@"url_preference"], 
                                              [[NSUserDefaults standardUserDefaults] stringForKey:@"username"]]];
	[asyncImage loadImageFromURL:avatarURL];
    [asyncImage setForImage:avatarImageView];
    avatarImageView.contentMode = UIViewContentModeScaleAspectFit;
    [asyncImage release];
    
    // update tabbar
    [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:NO];
} 

- (void)peseudoReload
{
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark TabBar

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    [myTabBar setSelectedItem:nil];
    //NSLog(@"%d", item.tag);
    switch (item.tag) {
        case 0:
            [[[[self.tabBarController.viewControllers objectAtIndex:1] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 1;
            break;
        case 1:
            [[[[self.tabBarController.viewControllers objectAtIndex:2] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 2;
            break;
        case 2: 
            [[[[self.tabBarController.viewControllers objectAtIndex:3] topViewController] navigationController] popToRootViewControllerAnimated:NO];
            self.tabBarController.selectedIndex = 3;
            break;
        case 3: 
            [AppDelegate updateTabBarItem:myTabBar withMailValue:-1 andUpdateMute:YES];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark NSURLConnectionDelegete

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
	[responseData setLength:0];
    
    // loading
	HUD.mode = MBProgressHUDModeDeterminate;
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{
    // loading
    [HUD hide:YES];
    
    /* Error message */
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil 
													message:NSLocalizedString(@"Unknown network error", nil)
												   delegate:self 
										  cancelButtonTitle:NSLocalizedString(@"OK", nil) 
										  otherButtonTitles:nil];
	[alert show];
	[alert release];	
    
    [responseData release];
    responseData = nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
	
	NSMutableArray *results = [responseString JSONValue];
    [responseString release];
    
    NSString *str = [[NSString alloc] initWithFormat:NSLocalizedString(@"You have %d new Mails", nil), [results count]];
    [self.start2Label setText:str];
    [AppDelegate updateTabBarItem:myTabBar withMailValue:[results count] andUpdateMute:NO];
    [str release];
    
    [responseData release];
    responseData = nil;
    
    // loading
    [HUD hide:YES];
}  

#pragma mark -
#pragma mark MBProgressHUDDelegate methods

- (void)hudWasHidden:(MBProgressHUD *)hud {
    // Remove HUD from screen when the HUD was hidded
    [HUD removeFromSuperview];
    [HUD release];
    HUD = nil;
}

@end
